package demo6;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Comparator;

public class TestDemo6 {

    public static void bubbleSort(Comparable[] comparables) {
        for (int i = 0; i < comparables.length - 1; i++) {
            for (int j = 0; j < comparables.length - 1 - i; j++) {
                if(comparables[j].compareTo(comparables[j + 1]) > 0) {
                    Comparable tmp = comparables[j];
                    comparables[j] = comparables[j + 1];
                    comparables[j + 1] = tmp;
                }
            }
        }
    }

    public static void main(String[] args) {
        Student[] students = new Student[3];
        students[0] = new Student("d", 19);
        students[1] = new Student("c", 15);
        students[2] = new Student("e", 13);
        NameComparator nameComparator = new NameComparator();
//        Arrays.sort(students, nameComparator);
        bubbleSort(students);
        System.out.println(Arrays.toString(students));
    }
    public static void main0(String[] args) {
        Student student1 = new Student("lyc", 19);
        Student student2 = new Student("lisi", 15);
//        System.out.println(student2.compareTo(student1));//不太好


//        AgeComparator ageComparator = new AgeComparator();
//        System.out.println(ageComparator.compare(student1, student2));
//        NameComparator nameComparator = new NameComparator();
//        System.out.println(nameComparator.compare(student1, student2));


    }
}

class Student implements Comparable<Student> {
    public String name;
    public int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
//不太好，因为如果要比较name，那么还要删除重新写一次，而下一次比较age也是同理,
    //这个是默认的比较方式
    @Override
    public int compareTo(Student o) {
        return -this.age + o.age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

class AgeComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.age - o2.age;
    }
}

class NameComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.name.compareTo(o2.name);
    }
}
